<?php

/**
 * Created by PhpStorm.
 * User: GadflyBSD
 * Date: 16/3/12
 * Time: 11:35
 */
class CustomerAction extends CommonAction{

	public function _initialize(){
		parent::_initialize();
	}

	public function index(){
		header("Location: ".$this->weixin->get_auth2_url(APP_URL.U('Customer/run', array('an' => I('get.an')))));
	}

	public function onePage(){
		if($this->checkWeixin()){
			switch(I('get.type')){
				case 'survey':
					$this->assign(M('WakaRealname')->where('rid='.I('get.rid'))->find());
					break;
				case 'register':
					break;
				case 'test':
					dump($_SESSION);
					break;
			}
			$this->display(I('get.type'));
		}else{
			header("Location: ".$this->weixin->get_auth2_url(APP_URL.__SELF__, 'snsapi_userinfo'));
		}
	}

	public function onePagePostAjax($post){
		switch($post['op']){
			case 'setSurvey':
				return D('Customer')->setSurvey($post);
			case 'register':
				return D('Customer')->registerUser($post);
		}
	}

	/**
	 * 乐享哇咔微信 订阅行为响应和自动回复消息
	 * @throws Exception
	 */
	public function replay(){
		Vendor('Weixin');
		$weixin = new Weixin('WAKA');
		$weixin->valid();
		if($weixin->checkSignature()){
			$data = $weixin->request();
			if($data && is_array($data)){
				if($data['MsgType'] == 'event' && $data['Event'] == 'unsubscribe')
					D('Public')->attention($data['FromUserName'], 'unsubscribe', 'WAKA');
				else
					D('Public')->attention($data['FromUserName'], 'subscribe', 'WAKA');
				switch($data['MsgType']){
					case 'text':
						$weixin->response($this->sendNews(), 'news');
						break;
					case 'image':
						$weixin->response($this->sendNews(), 'news');
						break;
					case 'voice':
						$weixin->response($this->sendNews(), 'news');
						break;
					case 'video':
						$weixin->response($this->sendNews(), 'news');
						break;
					case 'event':
						switch($data['Event']){
							case 'subscribe':
								$weixin->response($this->sendNews(), 'news');
								header("Location: ".APP_URL.U('Customer/Index', array('an' => 'bindWeixin')));
								break;
							case 'unsubscribe':
								break;
						}
						break;
				}
			}
		}
	}

	/**
	 * 创建微信端自定义菜单
	 */
	public function setMenu(){
		header("Content-type: text/html; charset=utf-8");
		Vendor('Weixin');
		$weixin = new Weixin('WAKA');
		$menu = array(
			'button'    => array(
				array(
					"type"  => "view",
					'name'  => '消费扫码',
					"url"   => APP_URL.U('Customer/Index', array('an' => 'scanQrCode')),
				),
				array(
					'name'      => '账户&账单',
					'sub_button'=> array(
						array(
							"type"  => "view",
							"name"  => "绑定微信",
							"url"   => APP_URL.U('Customer/Index', array('an' => 'bindWaka')),
						),
						array(
							"type"  => "view",
							"name"  => "绑定尽调员",
							"url"   => APP_URL.U('Customer/Index', array('an' => 'bindSurvey')),
						),
						array(
							"type"  => "view",
							"name"  => "个人信息",
							"url"   => APP_URL.U('Customer/Index', array('an' => 'userInfo')),
						),
						array(
							"type"  => "view",
							"name"  => "账单查询",
							"url"   => APP_URL.U('Customer/Index', array('an' => 'billSearch')),
						),
						array(
							"type"  => "view",
							"name"  => "消费查询",
							"url"   => APP_URL.U('Customer/Index', array('an' => 'consumeSearch')),
						),
					),
				),
				array(
					'name'      => '关于&帮助',
					'sub_button'=> array(
						array(
							"type"  => "view",
							"name"  => "客户端下载",
							"url"   => APP_URL.U('Customer/Index', array('an' => 'download')),
						),
						array(
							"type"  => "view",
							"name"  => "联系客服",
							"url"   => APP_URL.U('Customer/Index', array('an' => 'dkf')),
						),
						array(
							"type"  => "view",
							"name"  => "关于我们",
							"url"   => APP_URL.U('Customer/Index', array('an' => 'about')),
						),
					),
				),
			)
		);
		dump($weixin->custom_button('create', $menu));
	}

	protected function angularAjax($post){
		$info = session('waka');
		switch($post['op']){
			case 'sendSms':
				return $this->sendSms($post, 'WAKA');
			case 'getSession':
				$info = D('Public')->getSession($post['refresh']);
				log::write(json_encode_plus($info), 'WakaInfo');
				return $info['sideInfo'];
			case 'getUserInfo':
				return D('Customer')->getUserInfo();
			case 'setUserInfo':
				return D('Customer')->setUserInfo($post);
			case 'getWeixin':
				return D('Customer')->getWeixin();
			case 'setUserInfo':
				return D('Customer')->setUserInfo($post);
			case 'bindWaka':
				return D('Customer')->bindWaka($post);
			case 'bindSurvey':
				return D('Customer')->bindSurvey($post);
			case 'getShopInfo':
				return D('Customer')->getShopInfo($post['qrcode']);
			case 'getQrcodeData':
				return D('Customer')->getQrcodeData($post['qrcode']);
			case 'getSchoolList':
				return D('School', 'Logic')->getAllCategory();
		}
	}

	protected function angularGetAjax($get){

	}

	protected function angularPostAjax($post){
		$info = session('waka');
		switch($post['op']){
			case 'sendSms':
				return $this->sendSms($post, 'WAKA');
			case 'getSession':
				if($post['refresh']){
					$info['sideInfo'] = D('Public')->auth2user($info['openid']);
					session('waka', $info);
				}
				$info['sideInfo']['qrcodeUrl'] = U('Business/qrcode', array('s' => $info['sideInfo']['md5key']));
				$info['sideInfo']['errcode'] = 0;
				return $info['sideInfo'];
			case 'getUserInfo':
				return D('Customer')->getUserInfo();
			case 'getWeixin':
				return D('Customer')->getWeixin();
			case 'setUserInfo':
				return D('Customer')->setUserInfo($post);
			case 'bindWaka':
				return D('Customer')->bindWaka($post);
			case 'bindSurvey':
				return D('Customer')->bindSurvey($post);
			case 'getShopInfo':
				return D('Customer')->getShopInfo($post['qrcode']);
			case 'getQrcodeData':
				return D('Customer')->getQrcodeData($post['qrcode']);
			case 'getSchoolList':
				return D('School', 'logic')->getAllCategory();
		}
	}

	protected function validationAjax($post){
		switch($post['op']){
			case 'sms':
				Vendor('CtcSms');
				$sms = new CtcSms();
				return array('errcode' => 0, 'isUnique' =>$sms->verify(array('mobile' => $post['mobile'], 'code' => $post['mbcode'])));
			case 'wakaUserRemote':
				return D('Customer')->validation('wakaUserRemote', $post);
			case 'wakaUserLocal':
				return D('Customer')->validation('wakaUserLocal', $post);
		}
	}

	/**
	 * 关注和发信息给微信号时推送的新闻类图文消息的标题/说明/链接地址/图片等信息
	 * @param $param    所关注的微信号: Customer(乐享哇咔)/Business(哇咔商户, 默认)
	 *
	 * @return array
	 */
	private function sendNews(){
		return array(
			array(
				'Title'         => '您好！汪卡！',
				'Description'   => '汪卡APP安装地址...',
				'Url'           => 'http://www.wowcard.cn/download.html',
				'PicUrl'        => 'http://www.wowcard.cn/wechat/images/WechatBanner1.jpg',
			),
			array(
				'Title'         => '汪卡iOS端第一次运行操作说明',
				'Description'   => 'iPhone授权许可...',
				'Url'           => 'http://www.wowcard.cn/install_iOS.html',
				'PicUrl'        => 'http://www.wowcard.cn/wechat/images/WechatSecondBanner2.jpg',
			),
			array(
				'Title'         => '关于汪卡',
				'Description'   => '关于汪卡',
				'Url'           => 'http://www.wowcard.cn',
				'PicUrl'        => 'http://www.wowcard.cn/wechat/images/WechatSecondBanner3.jpg',
			),
		);
	}

	public function tryUpload(){
		echo uuid();
	}

	public function testPush(){
		/*$pushmsg = D('Pushmsg')->template(array(
				'type'  => 'survey',
				'id'    => '4028b881500aec8901500aee39c40000',
				'uid'   => 34,
			));
		$pushmsg = D('Pushmsg')->template(array(
			'type'  => 'survey',
			'id'    => '4028b881500aec8901500aee39c40000',
			'uid'   => 38,
		));
		$pushmsg = D('Pushmsg')->template(array(
			'type'  => 'confirm',
			'id'    => '297ebe0e5477682f015484690760001a',     //'297ebe0e542c3cf8015431887329000b',
			'uid'   => 2,    //1,
			'money' => '10.00',      //'500',
			'mobile'=> '15368176687',     //'13354631875',
		));
		$pushmsg = D('Pushmsg')->createShop(array(
			'openid'    => 'ol5M5vz3s-auECoDM5hXDPXzMTOo',
			'title'     => '测试用店铺一',
			'category'  => M('WangkaCategory')->where('id=16')->getField('title'),
			'mobile'    => '13354631875',
			'password'  => 'dddddddd',
		));*/
		$pushmsg = D('Pushmsg')->template(array(
			'type'  => 'survey',
			'id'    => '297ebe0e5506c1c9015509a1e64c0015',
			'uid'   => 5,
		));
		$this->ajax($pushmsg);
	}

	public function test(){
		header("Content-type: text/html; charset=utf-8");
		Vendor('ChinaPnr');
		$pnr = new ChinaPnr();
		/*$post = array(
			'user_mobile'   => '13354631875',
		);
		dump($pnr->securityCode($post));*/
		//$strd = '0074S9900990059CashReconciliation00060000600002024272014081120140812110000';
		$data = array(
			'user_name'     => '刘海明',
			'cert_id'       => '530103197510290651',
			'user_mobile'   => '13354631875',
			'sms_code'      => I('get.code'),
			'sms_order_date'=> date('Ymd'),
			'sms_order_id'  => I('get.order')
		);
		print_r($pnr->openAccount($data, 'preson'));
	}

	/**
	 * 测试发送短信验证码
	 */
	public function test0(){
		Vendor('ChinaPnr');
		$pnr = new ChinaPnr();
		$post = array(
			'user_mobile'   => I('get.mobile'),
			'user_cust_id'  => '6666000000000268',
		);
		$return = $pnr->securityCode($post, '101');
		dump($return);
	}

	/**
	 * 测试个人开户
	 */
	public function test1(){
		header("Content-type: text/html; charset=utf-8");
		Vendor('ChinaPnr');
		$pnr = new ChinaPnr();
		$data = array(
			'user_name'     => I('get.name'),
			'cert_id'       => I('get.cardid'),
			'user_mobile'   => I('get.mobile'),
			'sms_code'      => '666666',
			'sms_order_date'=> date('Ymd'),
			'sms_order_id'  => I('get.order')
		);
		dump($pnr->openAccount($data, 'preson'));
	}

	/**
	 * 充值
	 */
	public function test2(){
		Vendor('ChinaPnr');
		$pnr = new ChinaPnr();
		$post = array(
			'user_cust_id'  => I('get.cid'),
			'trans_amt'     => '2666.00',
		);
		print($pnr->recharge($post, '03090000', 'D', 'recharge'));
	}

	/**
	 * 企业对个人转账
	 */
	public function test3(){
		Vendor('ChinaPnr');
		$pnr = new ChinaPnr();
		$post = array(
			'out_cust_id'   => '6666000000000328',
			'out_acct_id'   => '404',
			'in_cust_id'    => '6666000000000313',
			'in_acct_id'    => '388',
			'transfer_amt'  => '150.00'
		);
		dump($pnr->transfer($post, 'BusinessSubAccount'));
	}

	/**
	 * 个人对个人转账
	 */
	public function test4(){
		Vendor('ChinaPnr');
		$pnr = new ChinaPnr();
		$post = array(
			'out_cust_id'   => '6666000000000268',
			'out_acct_id'   => '316',
			'in_cust_id'    => '6666000000000328',
			'in_acct_id'    => '404',
			'transfer_amt'  => '100.00'
		);
		dump($pnr->transfer($post));
	}

	/**
	 * 查账
	 */
	public function test5(){
		Vendor('ChinaPnr');
		$pnr = new ChinaPnr();
		$post = array(
			'user_cust_id' => I('get.cid'),
		);
		print_r($pnr->balance($post));
	}

	/**
	 * 测试取现绑卡
	 */
	public function test6(){
		Vendor('ChinaPnr');
		$pnr = new ChinaPnr();
		$post = array(
			'user_cust_id'  => '6666000000000328',
			'bank_id'       => '01050000',
			'card_no'       => '6210814868714631879',
			'dc_flag'       => 'D',
			'card_prov'     => '0053',
			'card_area'     => '5301',
			'is_default'    => '00000001',
		);
		dump($pnr->withdrawBindCard($post));
	}

	/**
	 * 测试提现
	 */
	public function test7(){
		Vendor('ChinaPnr');
		$pnr = new ChinaPnr();
		$post = array(
			'user_cust_id'  => '6666000000000328',
			'trans_amt'     => '25.00',
			'card_no'       => '6210814868714631879',
		);
		dump($pnr->withdraw($post, 't1'));
	}

	public function test8(){
		Vendor('ChinaPnr');
		$pnr = new ChinaPnr();
		$data = array(
			'apply_id'              => 'zdbusiness',
			'operate'               => 'add',
			'corp_type'             => 'c2',
			'corp_name'             => '昆明市经开区中道小额贷款股份有限公司',
			'social_credit_code'    => '9153010057980893X4',             // 企业的统一社会信用代码
			'license_start_date'    => '20110722',             // 企业的营业证照起始日期,精确到年月日
			'license_end_date'      => '99991231',               // 企业的营业证照结束日期,精确到年月日,99991231 表示永久
			'corp_business_address' => '昆明经开区出口加工区电子及信息产业物流功能区工业三区浦发路中道集团大厦',          // 企业的经营地址,中文应使用UTF-8 字符集 URLEncode 编码后传入
			'corp_reg_address'      => '昆明经开区出口加工区电子及信息产业物流功能区工业三区浦发路中道集团大厦',               // 企业的注册地址,中文应使用UTF-8 字符集 URLEncode 编码后传入
			'corp_fixed_telephone'  => '0871-63662858',           // 企业的固定电话
			'business_scope'        => '办理经开区域内各项小额贷款；为经开区域内小企业发展、管理、财务等提供咨询服务；其他经审查的业务（依法须经批准的项目，经相关部门批准后方可开展经营活动）',                 // 企业的经营范围,中文应使用UTF-8 字符集 URLEncode 编码后传入
			'controlling_shareholder' => '马武 金琳雁 朱建华 王硕 杨庆玲 杨家雄 陈花兰 黄蕊',      // 企业的控股股东,中文应使用必须UTF-8 字符集 URLEncode 编码后传入
			'legal_name'            => '马武',                     // 企业的法人姓名,中文应使用必须UTF-8 字符集 URLEncode 编码后传入
			'legal_cert_type'       => 'l1',        // 法人证件类型 l1:身份证 l2:护照 l3:军官证 l4:士兵证 l5:回乡证 l6:警官证 l7:台胞证 l8:其他
			'legal_cert_id'         => '530111196912280857',                  // 法人的证件号码,与证件类型对应
			'legal_mobile'          => '13908719181',                   // 法定代表人的手机号码
			'legal_cert_start_date' => '20120413',          // 法定代表人的证件起始日期,精确到年月日
			'legal_cert_end_date'   => '20320413',            // 法定代表人的证件结束日期,精确到年月日,99991231 表示永久
			'contact_name'          => '戴卫国',                   // 企业联系人的姓名,中文应使用UTF-8 字符集 URLEncode 编码后传入
			'contact_mobile'        => '18687519319',                 // 联系人的手机号码
			'contact_email'         => '358757091@qq.com',                  // 联系人的邮箱地址
			'bank_acct_name'        => '昆明市经开区中道小额贷款股份有限公司',                 // 企业开户银行账户名,需与企业名称保持一致,中文应使用UTF-8 字符集 URLEncode 编码后传入
			'bank_id'               => '03020000',                        // 充值/取现支持银行列表及代号
			'bank_acct_no'          => '7303210181700000177',                   // 企业开户银行账号
			'bank_branch'           => '昆明经开区支行',                    // 企业开户银行的支行名称,中文应使用UTF-8 字符集 URLEncode 编码后传入
			'bank_prov'             => '0053',                      // 银行卡开户省份
			'bank_area'             => '5301',
		);
		print($pnr->openAccount($data, 'business'));
	}

	/**
	 * 商品录入测试
	 */
	public function test9(){
		Vendor('ChinaPnr');
		$pnr = new ChinaPnr();
		$data = array(
			'product_id'        => time(),
			'product_amt'       => '10000.00',
			'product_periods'   => '12',
			'product_start_time'=> '20170101010101',
			'product_end_time'  => '20171231235959',
			'product_location'  => '0053',
		);
		dump($pnr->product($data));
	}

	public function getUser(){
		Vendor('Weixin');
		$weixin = new Weixin('WKSHOP');
		dump($weixin->get_openid_info(I('get.openid')));
	}

	public function getSurveySchool(){
		$bind = M('WakaBind');
		$list = $bind->where('role="survey"')->field('bid, survey_name, survey_id')->select();
		echo '<ul>';
		foreach($list AS $val){
			$where = array('id' => $val['survey_id']);
			$schoolcode = M('user','t_','mysql://weixin_user:weixin_HYCT0871@120.25.67.227/stages')->where($where)->getField('schoolcode');
			$bind->where('bid='.$val['bid'])->setField('survey_school', $schoolcode);
			echo '<li> ID: '.$val['bid']. ' Survey: '.$val['survey_name'].', School: '.$schoolcode.', SQL: '.$bind->getLastSql().'</li>';
		}
		echo '</ul>';
	}

	/**
	 * 同步APP端尽调员实名数据
	 */
	public function syncSurveyRelanme(){
		$bind = M('WakaBind');
		$realnameTable = M('WakaRealname');
		$target = '/Public/Upload/Customer';
		$uuid = $bind->field('bid, student_id')->select();
		foreach($uuid AS $val){
			$where = array('uuid' => $val['student_id']);
			$user = M('RealnameCustomerView','t_','mysql://weixin_user:weixin_HYCT0871@120.25.67.227/stages')->where($where)->find();
			foreach($user AS $key => $vo){
				if(in_array($key, array('headimgurl', 'idcard_url_1', 'idcard_url_2', 'yikatong_url', 'student_card_url', 'other_url'))){
					if(!is_null($vo)){
						$res = D('Public')->getMedia($vo, $target);
						if($res['type'] == 'error')
							$post[$key] = null;
						else
							$post[$key] = 'http://sta.mywoka.com'.$res['url'];
					}
				}elseif($key != 'id'){
					$post[$key] = $vo;
				}
			}
			if($realnameTable->where('uuid="'.$post['uuid'].'"')->count() == 0){
				$rec = D('Public')->curd(array(
					'model' => $realnameTable,
					'type'  => 'add',
					'data'  => $post,
				));
			}else{
				$rec = D('Public')->curd(array(
					'model' => $realnameTable,
					'type'  => 'save',
					'where' => 'uuid="'.$post['uuid'].'"',
					'data'  => $post,
				));
			}
			if($rec['errcode'] == '0'){
				$bind->where('bid='.$val['bid'])->setField('rid', $rec['pk']);
			}
			dump($rec);
		}
	}

	/**
	 * 同步APP端实名认证数据
	 */
	public function syncCustomerRealname(){
		$realnameTable = M('WakaRealname');
		$realname = M('RealnameIdentify','t_','mysql://weixin_user:weixin_HYCT0871@120.25.67.227/stages');
		$target = '/Public/Upload/Customer';
		$where = 'state IS NOT NULL';
		$user = M('RealnameCustomerView','t_','mysql://weixin_user:weixin_HYCT0871@120.25.67.227/stages')->where($where)->select();
		foreach($user AS $val){
			foreach($val AS $key => $vo){
				if(in_array($key, array('headimgurl', 'idcard_url_1', 'idcard_url_2', 'yikatong_url', 'student_card_url', 'other_url'))){
					if(!is_null($vo)){
						$res = D('Public')->getMedia($vo, $target);
						if($res['type'] == 'error')
							$post[$key] = null;
						else
							$post[$key] = 'http://sta.mywoka.com'.$res['url'];
					}
				}elseif($key != 'id'){
					$post[$key] = $vo;
				}
			}
			$data = $realname->where('customerid="'.$post['uuid'].'"')->field('wx_agreement_pic, wx_hezhao_pic, wx_other_pic')->find();
			$post['survey_1_url'] = $data['wx_agreement_pic'];
			$post['survey_2_url'] = $data['wx_hezhao_pic'];
			$post['survey_other_url'] = $data['wx_other_pic'];
			if($realnameTable->where('uuid="'.$post['uuid'].'"')->count() == 0){
				$rec = D('Public')->curd(array(
					'model' => $realnameTable,
					'type'  => 'add',
					'data'  => $post,
				));
			}else{
				$rec = D('Public')->curd(array(
					'model' => $realnameTable,
					'type'  => 'save',
					'where' => 'uuid="'.$post['uuid'].'"',
					'data'  => $post,
				));
			}
			dump($rec);
		}
	}

}